package com.nt.redisdemo.nt.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nt.redisdemo.nt.entity.KeyCompareVO;
import com.nt.redisdemo.nt.service.KeyCompareService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class KeyCompareServiceImpl implements KeyCompareService {

    /**
     * 将 List<KeyCompareVO> 转化为 JSON 字符串
     *
     * @param keyCompareVOList 输入的 KeyCompareVO 列表
     * @return 转化后的 JSON 字符串
     */
    @Override
    public String convertToJson(List<KeyCompareVO> keyCompareVOList) {
        // 调用递归方法生成嵌套 Map
        Map<String, Object> resultMap = convertToNestedMap(keyCompareVOList);

        // 使用 Jackson 将 Map 转换为 JSON 字符串
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.writeValueAsString(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return "{\"error\":\"Failed to convert to JSON\"}";
        }
    }

    /**
     * 递归方法：将 List<KeyCompareVO> 转化为嵌套的 Map 结构
     *
     * @param keyCompareVOList 输入的 KeyCompareVO 列表
     * @return 转化后的嵌套 Map
     */
    private Map<String, Object> convertToNestedMap(List<KeyCompareVO> keyCompareVOList) {
        Map<String, Object> resultMap = new HashMap<>();
        if (keyCompareVOList == null || keyCompareVOList.isEmpty()) {
            return resultMap;
        }

        for (KeyCompareVO vo : keyCompareVOList) {
            if (vo.getFiledCode() != null) {
                // 如果有 children，则递归生成子级 Map
                if (vo.getChildren() != null && !vo.getChildren().isEmpty()) {
                    resultMap.put(vo.getFiledCode(), convertToNestedMap(vo.getChildren()));
                } else {
                    // 如果没有 children，则直接设置 fieldName
                    resultMap.put(vo.getFiledCode(), vo.getFieldName());
                }
            }
        }
        return resultMap;
    }

}
